package com.xja.boke.controller;

import com.xja.boke.entity.User;
import com.xja.boke.service.UserService;
import com.xja.boke.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录 根据名字查询
     * @param user
     * @param session
     * @return
     */
    @GetMapping("login")
    public PageResult login(User user, HttpSession session) {
        User loginInfo = userService.selectByName(user.getUsername());
        if (loginInfo == null) {
            return PageResult.none("用户名错误");
        }
        if (!loginInfo.getPassword().equals(user.getPassword())) {
            return PageResult.none("密码错误");
        }
        session.setAttribute("loginInfo", loginInfo);
        return PageResult.success("成功", null);
    }

    /**
     * 注册
     * @return
     */
    @PostMapping("register")
    public PageResult addChatuser(@RequestBody User user, HttpSession session) {
        int g= (int) session.getAttribute("g");
        if (g==1){
            return PageResult.none("注册失败");
        }
       userService.insertSelective(user);
        return PageResult.success("注册成功",null);
    }
    /**
     * 验证账户名是否重复
     * @return
     */
    @GetMapping("findUserId")
    public PageResult findUserId(String username,HttpSession session) {
        User user = userService.selectByName(username);
        if (user==null){
            session.setAttribute("g",2);
            return PageResult.success("账户名可用",null);
        }else {
            session.setAttribute("g",1);
            return PageResult.none("账户名不可用");
        }
    }
}
